package com.github.binarywang.demo.wx.mp.intceptor;

import com.github.binarywang.demo.wx.mp.annotation.ApiIdempotence;
import com.github.binarywang.demo.wx.mp.service.RedisService;
import me.chanjar.weixin.common.redis.WxRedisOps;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName ApiIdempotenceIntceptor
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/4/5 17:54
 * @Version 1.0
 */
//@Component
//@Aspect
public class ApiIdempotenceIntceptor{


    private static final Logger LOGGER = LoggerFactory.getLogger(ApiIdempotenceIntceptor.class);
    //对包下所有的controller结尾的类的所有方法增强
    private final String executeExpr = "execution(*com.github.binarywang.demo.wx.mp.controller.*(..))";

    @Pointcut("@annotation(com.github.binarywang.demo.wx.mp.annotation.ApiIdempotence)")
    public void operationLog() {
    }
    @Resource
    private RedisService redisService;

    @Before(value = "operationLog()")
    public void processLog(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String methodName = method.getName();
        LocalVariableTableParameterNameDiscoverer paramNames = new LocalVariableTableParameterNameDiscoverer();
        String[] params = paramNames.getParameterNames(method);

        boolean methodAnn = method.isAnnotationPresent(ApiIdempotence.class);

        if(methodAnn && method.getAnnotation(ApiIdempotence.class).value()) {

            ApiIdempotence idempotence = method.getAnnotation(ApiIdempotence.class);
            String[] params1 = idempotence.params();
            Object[] pointArgs = joinPoint.getArgs();
            
            String redisKey = Arrays.stream(pointArgs).filter(Objects::nonNull)
                    .map(String::valueOf).collect(Collectors.joining(":"));
            String val = redisService.get(redisKey);
            if(StringUtils.isEmpty(val) || !"3".equals(val)) {
                redisService.setEx(redisKey,"3",30);
                return;
            }

            throw new RuntimeException("中段执行");
        }

    }
}
